package pl.edu.mimuw.irs.core.model.analysis;

import java.util.LinkedHashSet;
import java.util.Set;

import pl.edu.mimuw.irs.core.global.IDManager;
import pl.edu.mimuw.irs.core.model.design.processing.Requirement;
import pl.edu.mimuw.irs.core.model.petrinet.Place;
import pl.edu.mimuw.irs.core.util.Position;

public class RequirementPlace extends Place implements IRegistry {

	private static final long serialVersionUID = 905584428737105972L;

	public static final int DECREASED_TOKENS_NUMBER = 1;
	
	// *** Attributes
	
	private Requirement requirement;
	private Set<ResourcePlace> meetingResources;
	private Registry registry;
	public Requirement getRequirement() {
		return requirement;
	}
	public Set<ResourcePlace> getMeetingResources() {
		if (meetingResources == null) meetingResources = new LinkedHashSet<ResourcePlace>();
		return meetingResources;
	}
	public Registry getRegistry() {
		if (registry == null) registry = new Registry();
		return registry;
	}

	// *** Constructors
	
	public RequirementPlace(IDManager idManager, Requirement requirement, Position position, int tokens) {
		super(idManager, idManager.getPrefixedNewId("Avl" + requirement.getName()), 
				position, tokens);
		this.requirement = requirement;
	}
	
	public RequirementPlace(IDManager idManager, Requirement requirement, Position position) {
		this(idManager, requirement, position, 0);
	}
	
	// *** Methods
	
	@Override
	public void setTokens(int tokens) {
		int oldTokens = getTokens();
		super.setTokens(tokens);
		if (oldTokens < tokens) {
			notifyListeners(DECREASED_TOKENS_NUMBER, getTokens(), this);
		}
	}
	
	@Override
	public void addTokens(int num) {
		super.addTokens(num);
		if (num < 0) {
			notifyListeners(DECREASED_TOKENS_NUMBER, getTokens(), this);
		}
	}
	
	@Override
	public void register(Object propertyId, IListener listener) {
		getRegistry().register(propertyId, listener);
	}
	
	@Override
	public void unregister(Object propertyId, IListener listener) {
		getRegistry().unregister(propertyId, listener);
	}
	
	@Override
	public void notifyListeners(Object propertyId, Object newValue,
			IRegistry registry) {
		getRegistry().notifyListeners(propertyId, newValue, registry);
	}
	
	@Override
	public boolean isRegistered(Object propertyId, IListener listener) {
		return getRegistry().isRegistered(propertyId, listener);
	}
	
	@Override
	public String toString() {
		return "@" + getRequirement() + "@";
	}
}
